<?php

namespace app\api\controller;

use app\payment\PayFactory;
use app\services\ConfigService;
use app\services\OrderService;
use app\services\UserService;
use app\services\WorkService;
use plugin\admin\app\model\Order;
use support\Db;
use support\Log;
use support\Paypal;
use support\Request;
use Yansongda\Pay\Pay;

class NotifyController
{
    public function handle(Request $request)
    {
        print_r($request->post());
        Db::beginTransaction();
        try {
            Pay::config(ConfigService::getPaymentConfig(PayFactory::WECHAT));

            $result = Pay::wechat()->callback($request->post())->toArray();

            print_r($result);

            if ($result['resource']['ciphertext']['trade_state'] == 'SUCCESS') {
                $orderNo = $result['resource']['ciphertext']['out_trade_no'];

                $order = Order::where('order_no', $orderNo)->first();

                if ($order['status'] == Order::STATUS_WAITING_PAY) {
                    switch ($order['type']) {
                        case Order::TYPE_GOODS:
                        case Order::TYPE_GIFT:
                            OrderService::paySuccess($orderNo);
                            break;
                        case Order::TYPE_RECHARGE:
                            OrderService::rechargeSuccess($orderNo);
                            break;
                        case Order::TYPE_UPGRADE_VIP:
                            UserService::paySuccess($orderNo);
                            break;
                        case Order::TYPE_WORK:
                            WorkService::paySuccess($orderNo);
                            break;
                    }
                }

                Db::commit();
                return Pay::wechat()->success();
            }

        } catch (\Exception $e) {
            echo $e->getMessage() . $e->getTraceAsString();
            Db::rollBack();
        }

    }

    public function handleAlipay(Request $request)
    {
        Db::beginTransaction();
        try {
            Pay::config(ConfigService::getPaymentConfig(PayFactory::ALIPAY));

            $result = Pay::alipay()->callback($request->post())->toArray();

            if ($result['trade_status'] == 'TRADE_SUCCESS') {
                $orderNo = $result['out_trade_no'];

                $order = Order::where('order_no', $orderNo)->first();

                if ($order['status'] == Order::STATUS_WAITING_PAY) {
                    switch ($order['type']) {
                        case Order::TYPE_GOODS:
                            OrderService::paySuccess($orderNo);
                            break;
                    }
                }

                Db::commit();
                return Pay::alipay()->success();
            }

        } catch (\Exception $e) {
            Log::info($e->getMessage() . $e->getTraceAsString());
            echo $e->getMessage() . $e->getTraceAsString();
            Db::rollBack();
        }

    }

    public function handlePaypal(Request $request)
    {
        Db::beginTransaction();
        try {

            $config = ConfigService::getByGroup('paypal');

            $pay = new Paypal(
                $config['paypal_client_id'],
                $config['paypal_client_secret'],
                true
            );

            $isValid = $pay->verifyWebhook(
                $config['paypal_webhook_id'],
                $request->header(),
                $request->rawBody()
            );

            $data = $request->post('resource');

            print_r($data);

            if ($isValid) {
                if ($data['status'] == 'COMPLETED') {
                    $orderNo = $data['custom_id']; // 假设 custom_id 存储的是订单号

                    $order = Order::where('order_no', $orderNo)->first();

                    if ($order['status'] == Order::STATUS_WAITING_PAY) {
                        switch ($order['type']) {
                            case Order::TYPE_GOODS:
                            case Order::TYPE_GIFT:
                                OrderService::paySuccess($orderNo);
                                break;
                            case Order::TYPE_RECHARGE:
                                OrderService::rechargeSuccess($orderNo);
                                break;
                            case Order::TYPE_UPGRADE_VIP:
                                UserService::paySuccess($orderNo);
                                break;
                            case Order::TYPE_WORK:
                                WorkService::paySuccess($orderNo);
                                break;
                        }
                    }

                    Db::commit();
                    return json_encode(['success' => true]);
                } elseif ($data['status'] == 'APPROVED') {
                    $orderNo = $data['purchase_units'][0]['custom_id'];
                    $paymentId = $data['id'];

                    // 调用 PayPal API 进行捕获操作
                    $captureResult = $pay->capturePayment($paymentId);

                    if ($captureResult['status'] == 'COMPLETED') {
                        $order = Order::where('order_no', $orderNo)->first();

                        if ($order['status'] == Order::STATUS_WAITING_PAY) {
                            switch ($order['type']) {
                                case Order::TYPE_GOODS:
                                case Order::TYPE_GIFT:
                                    OrderService::paySuccess($orderNo);
                                    break;
                                case Order::TYPE_RECHARGE:
                                    OrderService::rechargeSuccess($orderNo);
                                    break;
                                case Order::TYPE_UPGRADE_VIP:
                                    UserService::paySuccess($orderNo);
                                    break;
                                case Order::TYPE_WORK:
                                    WorkService::paySuccess($orderNo);
                                    break;
                            }
                        }

                        Db::commit();
                        return json_encode(['success' => true]);
                    } else {
                        Log::info("Failed to capture PayPal payment for order: " . $orderNo);
                        Db::rollBack();
                        return json_encode(['error' => 'Failed to capture payment']);
                    }
                }
            }


        } catch (\Exception $e) {
            Log::info($e->getMessage() . $e->getTraceAsString());
            echo $e->getMessage() . $e->getTraceAsString();
            Db::rollBack();
        }
    }
}